package com.xsq.wifi.utils;

import android.util.Log;
import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class VideoTransferManager {
    private static final String TAG = "VideoTransferManager";
    private static final byte PROTOCOL_VERSION = 0x01;
    private static final int HEADER_SIZE = 12;
    private static final int CHUNK_SIZE = 1024 * 64; // 64KB每块
    private static final int RECONNECT_MAX_RETRY = 3; // 最大重试次数
    private static final int SOCKET_TIMEOUT = 30000; // 30秒超时

    private Socket socket;
    private OutputStream outputStream;
    private volatile boolean isTransferring = false;
    private volatile boolean shouldStop = false;

    public interface TransferCallback {
        void onTransferProgress(int progress);
        void onTransferSuccess();
        void onTransferFailure(String error);
    }

    public void startTransfer(File aviFile, String serverIp, int serverPort, TransferCallback callback) {
        if (isTransferring) {
            callback.onTransferFailure("已有传输正在进行");
            return;
        }

        new Thread(() -> {
            isTransferring = true;
            shouldStop = false;
            int retryCount = 0;
            boolean transferSuccess = false;

            while (retryCount < RECONNECT_MAX_RETRY && !transferSuccess && !shouldStop) {
                try {
                    // 建立长连接
                    establishConnection(serverIp, serverPort);

                    // 传输文件
                    transferFile(aviFile, callback);

                    transferSuccess = true;
                    callback.onTransferSuccess();
                } catch (IOException e) {
                    retryCount++;
                    Log.e(TAG, "传输失败，尝试重连 (" + retryCount + "/" + RECONNECT_MAX_RETRY + ")", e);

                    if (retryCount < RECONNECT_MAX_RETRY && !shouldStop) {
                        try {
                            Thread.sleep(2000); // 等待2秒后重试
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        callback.onTransferFailure("传输失败: " + e.getMessage());
                    }
                } finally {
                    closeConnection();
                }
            }

            isTransferring = false;
        }).start();
    }

    public void stopTransfer() {
        shouldStop = true;
    }

    private void establishConnection(String serverIp, int serverPort) throws IOException {
        socket = new Socket();
        socket.setSoTimeout(SOCKET_TIMEOUT);
        socket.connect(new java.net.InetSocketAddress(serverIp, serverPort), SOCKET_TIMEOUT);
        outputStream = socket.getOutputStream();
    }

    private void transferFile(File aviFile, TransferCallback callback) throws IOException {
        try (FileInputStream fileInputStream = new FileInputStream(aviFile)) {
            long fileSize = aviFile.length();
            int totalChunks = (int) Math.ceil((double) fileSize / CHUNK_SIZE);
            int chunkIndex = 0;
            byte[] buffer = new byte[CHUNK_SIZE];

            // 发送文件信息头
            sendFileHeader(outputStream, fileSize, aviFile.getName());

            // 分块传输
            int bytesRead;
            while (!shouldStop && (bytesRead = fileInputStream.read(buffer)) != -1) {
                if (socket.isClosed()) {
                    throw new IOException("连接已关闭");
                }

                // 构建协议头
                ByteBuffer header = ByteBuffer.allocate(HEADER_SIZE)
                        .order(ByteOrder.BIG_ENDIAN)
                        .put(PROTOCOL_VERSION)
                        .put(ProtocolConstants.CMD_FILETRANS_DATA)
                        .putShort((short) 0x0000) // control字段
                        .putInt(bytesRead)
                        .putInt(chunkIndex);

                // 发送数据
                outputStream.write(header.array());
                outputStream.write(buffer, 0, bytesRead);
                outputStream.flush();

                chunkIndex++;
                int progress = (int) ((chunkIndex * 100) / totalChunks);
                callback.onTransferProgress(progress);
            }
        }
    }

    private void sendFileHeader(OutputStream os, long fileSize, String fileName) throws IOException {
        ByteBuffer header = ByteBuffer.allocate(HEADER_SIZE + fileName.length())
                .order(ByteOrder.BIG_ENDIAN)
                .put(PROTOCOL_VERSION)
                .put(ProtocolConstants.CMD_FILETRANS_DATA)
                .putShort((short) 0x0001) // 文件信息头标识
                .putInt(fileName.getBytes().length)
                .putInt((int) fileSize) // 注意文件大小限制
                .put(fileName.getBytes());

        os.write(header.array());
        os.flush();
    }

    private void closeConnection() {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            Log.e(TAG, "关闭输出流失败", e);
        }

        try {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            Log.e(TAG, "关闭socket失败", e);
        }
    }

    private static class ProtocolConstants {
        static final byte CMD_FILETRANS_DATA = 0x02;
    }
}